package jinyilw.swing.rlaf.ui;

import jinyilw.swing.ComponentTools;
import jinyilw.swing.graphics.RenderingConfig;
import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.JComponent;
import javax.swing.JToolTip;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicHTML;
import javax.swing.plaf.basic.BasicToolTipUI;
import javax.swing.text.View;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;

/**
 * @author Jinyi
 */
public class RToolTipUI extends BasicToolTipUI
{
	static RToolTipUI rToolTipUI;
	private final RenderingConfig renderingConfig = new RenderingConfig();

	public static ComponentUI createUI(JComponent c)
	{
		if (rToolTipUI == null)
			rToolTipUI = new RToolTipUI();
		return rToolTipUI;
	}

	@Override
	public void installUI(JComponent c)
	{
		super.installUI(c);
	}

	@Override
	public void update(Graphics g, JComponent c)
	{
		Graphics2D g2d = (Graphics2D) g;
		renderingConfig.setTextAADrawing(g2d);
		paint(g, c);
		renderingConfig.resetTextAADrawing(g2d);
	}
	@Override
	public void paint(Graphics g, JComponent c)
	{
		Font font = c.getFont();
		FontMetrics metrics = ComponentTools.getFontMetrics(c, g, font);
		Dimension size = c.getSize();
		String tipText = ((JToolTip) c).getTipText();
		if (tipText == null)
			tipText = "";

		Insets insets = c.getInsets();
		Rectangle paintTextR = new Rectangle(insets.left + 3, insets.top,
				size.width - (insets.left + insets.right) - 6,
				size.height - (insets.top + insets.bottom));
		View v = (View) c.getClientProperty(BasicHTML.propertyKey);
		if (c.isOpaque())
		{
			g.setColor(v == null
					? RThemeColor.colorSet.bgColor
					: c.getBackground());
			g.fillRoundRect(1, 1, c.getWidth() - 2, c.getHeight() - 2, 3, 3);
		}
		if (v != null)
		{
			v.paint(g, paintTextR);
		} else
		{
			g.setColor(RThemeColor.colorSet.textColor);
			g.setFont(font);
			g.drawString(tipText, paintTextR.x,
					paintTextR.y + metrics.getAscent());
		}
	}
}
